package com.lecture.excel;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

public class ExcelFillCellMergeStrategy extends AbstractMergeStrategy {
    /**
     * 分组，每几行合并一次
     */
    private List<List<Integer>> mergeColDataGroupCountList;

    /**
     * 目标合并列index
     */
    private List<Integer> targetColumnIndex;

    /**
     * 需要开始合并单元格的首行index
     */
    private Integer rowIndex = -1;

    public ExcelFillCellMergeStrategy(List<List<String>> mergeColDataList, List<Integer> targetColumnIndex) {
        this.mergeColDataGroupCountList = getGroupCountList(mergeColDataList);
        this.targetColumnIndex = targetColumnIndex;
    }

    /**
     * @param sheet 当前工作表对象
     * @param cell 当前正在写入的单元格
     * @param head 该单元格对应的列头信息
     * @param relativeRowIndex 该单元格 相对于数据区域的行索引
     */
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if (rowIndex == -1) {
            rowIndex = cell.getRowIndex();
        }

        // 仅处理首行且在目标列中的单元格
        if (cell.getRowIndex() == rowIndex && targetColumnIndex.contains(cell.getColumnIndex())) {
            AtomicInteger i = new AtomicInteger(0);
            Optional<Integer> first = targetColumnIndex.stream().filter(col -> {
                i.getAndIncrement();
                return col.equals(cell.getColumnIndex());
            }).findFirst();

            first.ifPresent(targetCol -> mergeGroupColumn(sheet, targetCol));
        }
    }

    private void mergeGroupColumn(Sheet sheet, Integer index) {
        if (mergeColDataGroupCountList == null || mergeColDataGroupCountList.isEmpty()) {
            return;
        }

        int targetIndex = targetColumnIndex.indexOf(index);
        if (targetIndex == -1 || targetIndex >= mergeColDataGroupCountList.size()) {
            return; // 避免索引越界
        }

        int rowCount = rowIndex;
        for (Integer count : mergeColDataGroupCountList.get(targetIndex)) {
            if (count == 1) {
                rowCount += count;
                continue;
            }
            // 合并单元格
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1,
                    targetColumnIndex.get(targetIndex), targetColumnIndex.get(targetIndex));
            sheet.addMergedRegionUnsafe(cellRangeAddress);
            rowCount += count;
        }
    }

    /**
     * 该方法将目标列根据值是否相同连续可合并，存储可合并的行数
     */
    private List<List<Integer>> getGroupCountList(List<List<String>> exportDataList) {
        if (CollUtil.isEmpty(exportDataList)) {
            return new ArrayList<>();
        }

        List<List<Integer>> groupCountListList = new ArrayList<>();
        for (List<String> dataList : exportDataList) {
            List<Integer> groupCountList = new ArrayList<>();
            int count = 1;
            Collections.sort(dataList);
            for (int i = 1; i < dataList.size(); i++) {
                if (dataList.get(i).equals(dataList.get(i - 1))) {
                    count++;
                } else {
                    groupCountList.add(count);
                    count = 1;
                }
            }
            // 处理完最后一条后
            groupCountList.add(count);
            groupCountListList.add(groupCountList);
        }
        return groupCountListList;
    }
}

